<?php

namespace addons\zzyy\controller\api;

use addons\zzyy\module\Weixin;
use app\admin\model\zzyy\ZzyyRechargeSetting;
use app\admin\model\zzyy\ZzyyReserve;
use app\admin\model\zzyy\ZzyyThird;
use app\admin\model\zzyy\ZzyyTransaction;
use app\admin\model\zzyy\ZzyyUserBalance;
use app\admin\model\zzyy\ZzyyUserExtend;

class Payment extends \app\common\controller\Api
{
    protected $noNeedLogin = ['*'];

    public function createTransaction()
    {
        $user = $this->auth->getUser();

        $type = $this->request->post('type');

        $fee = 0;
        $itemKey = $this->request->post('item_key');

        if (ZzyyTransaction::TRANS_TYPE_RECHARGE == $type) {    // 余额充值
            $recharge = ZzyyRechargeSetting::get($itemKey);
            $fee = $recharge->num;
        } else if (ZzyyTransaction::TRANS_TYPE_DIRECT_BUY == $type) {   //直接预约
            $reserve = ZzyyReserve::get($itemKey);
            $fee = $reserve->fee;
        }

        $transaction = ZzyyTransaction::create([
            'out_trade_no' => (function () {
                list($usec, $sec) = explode(" ", microtime());
                $usec = substr(str_replace('0.', '', $usec), 0 ,4);
                $str  = rand(10,99);
                return date("YmdHis").$usec.$str;
            })(),
            'fee' => $fee,
            'status' => ZzyyTransaction::STATUS_CREATE,
            'user_id' => $user->id,
            'type' => $type,
        ]);

        $userThird = ZzyyThird::where('user_id', $user->id)->find();

        $notifyUrl = url('/addons/zzyy/api.payment/notice', [], false, true);
        $config = Weixin::getInstance()->jsapi($transaction->out_trade_no, $transaction->fee, $userThird->openid, $notifyUrl, $user->username . '用户充值的定单');
        $config['transaction_id'] = $transaction->id;
        $this->success('成功', $config);
    }

    public function notice()
    {
        $weixin = Weixin::getInstance();
        $result = $weixin->notify();

        if (false == $result) {
            $weixin->returnHttpCode(false, '通知接收失败或者解密失败');
        }

        $outTradeNo = $result['out_trade_no'];
        $transaction = ZzyyTransaction::where('out_trade_no', $outTradeNo)->find();

        //微信出现多次发起回调的问题, 已经支付成功，就停止后面的操作
        if (ZzyyTransaction::STATUS_SUCCESS == $transaction->status) {
            $weixin->returnHttpCode(true);
        }
        if (ZzyyTransaction::STATUS_REFUND == $transaction->status or ZzyyTransaction::STATUS_FAIL == $transaction->status) {
            exit;
        }
        if ($result['trade_state'] == 'SUCCESS') {
            $transaction->status = ZzyyTransaction::STATUS_SUCCESS;
            $transaction->transaction_no = $result['transaction_id'];
            $transaction->save();

            $weixin->returnHttpCode(true);

        } else {
            $transaction->status = ZzyyTransaction::STATUS_FAIL;
            $transaction->save();
            $weixin->returnHttpCode(false, '支付失败');
        }
    }

    public function checkTransaction()
    {
        $transactionId = $this->request->get('transaction_id');
        $userId = $this->auth->getUser()->id;

        sleep(3); // 给出后端回调的时间  最好的方式还是用socket, 不过这里为了简化用户的IT部署，要不要建一个websocket服务器

        $transaction = ZzyyTransaction::get($transactionId);

        if (ZzyyTransaction::STATUS_SUCCESS == $transaction->status) {
            $this->success('支付成功');
        }

        if (ZzyyTransaction::STATUS_CREATE == $transaction->status) {
            $this->result('订单未支付', null, 2);
        }

        if (ZzyyTransaction::STATUS_FAIL == $transaction->status) {
            $this->error('订单支付失败');
        }
    }

    public function balancePay()
    {
        $post = $this->request->post();
        $user = $this->auth->getUser();
        $userId = $user->id ?? 3;

        $userExtend = ZzyyUserExtend::where('user_id', $userId)->find();

        $subNum = $post['price'];
        if ($userExtend->balance < $subNum) {
            $this->error('余额不足');
        }
        $afterValue = $userExtend->balance - $subNum;

        $balance = new ZzyyUserBalance();
        $lastId = $balance->insertGetId([
            'user_id' => $userId,
            'type' => ZzyyUserBalance::TYPE_CONSUME, // -1=消费
            'value' => $subNum,
            'before_value' => $userExtend->balance,
            'after_value' => $afterValue,
            'createtime' => time(),
            'updatetime' => time()
        ]);

        $userExtend->balance = $afterValue;
        $userExtend->save();

        $this->success('ok', ['balance_id' => $lastId]);
    }



}
